package com.l024.framework.adapter;

import android.view.ViewGroup;
import android.widget.Adapter;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * 万能适配器
 */
public class CommonAdapter<T> extends RecyclerView.Adapter<CommonViewHolder>{

    private List<T> mList;

    private OnBindDataListener<T> onBindDataListener;
    private OnMoreBindDataListener<T> onMoreBindDataListener;

    public CommonAdapter(List<T> mList, OnBindDataListener<T> onBindDataListener) {
        this.mList = mList;
        this.onBindDataListener = onBindDataListener;
    }

    public CommonAdapter(List<T> mList, OnMoreBindDataListener<T> onMoreBindDataListener) {
        this.mList = mList;
        this.onBindDataListener = onMoreBindDataListener;
        this.onMoreBindDataListener = onMoreBindDataListener;
    }

    //绑定数据
    public interface OnBindDataListener<T>{
        //绑定数据
        void onBindViewHolder(T model,CommonViewHolder commonViewHolder,int type,int position);
        //返回布局
        int getLayoutId(int type);
    }

    //绑定多类型数据
    public interface  OnMoreBindDataListener<T> extends OnBindDataListener<T>{
        int getItemType(int posistion);
    }

    @Override
    public int getItemViewType(int position) {
        if(onMoreBindDataListener!=null){
            onMoreBindDataListener.getItemType(position);
        }
        return 0;
    }

    @NonNull
    @Override
    public CommonViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //获取ViewHolder
        int layoutId = onBindDataListener.getLayoutId(viewType);
        CommonViewHolder viewHolder = CommonViewHolder.getViewHolder(parent, layoutId);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull CommonViewHolder holder, int position) {
        //getItemViewType()得到当前item的类型
        onBindDataListener.onBindViewHolder(mList.get(position),holder,getItemViewType(position),position);
    }

    @Override
    public int getItemCount() {
        return mList==null?0:mList.size();
    }
}
